document.getElementById("multi-li").focus();
//导航栏按钮
var curButtionID = "";
var navIconList = [];
var tableButtonLiArr = document.getElementsByClassName('tablebutton-container');
var tableButtonArr = document.getElementsByClassName('tableButton');

// var multiAlt = true;
function clickMultiButton(){
  // var buttonID = (multiAlt)?"multi-drop":"multi-drop-state";
  if(document.getElementById("multi-drop-state").style.display=="block"){
    document.getElementById("multi-drop-state").style.display="none";
    document.getElementById("multi-drop").style.display="block";
  }
  var buttonID = "multi-drop";
  var buttonClass = "dropdown-section";
  changestyle(buttonID);
  setDropClassState(buttonID,buttonClass);
  curButtionID = buttonID;
}
function clickTemplateButton(){
  var buttonID = "template-drop";
  var buttonClass = "dropdown-section";
  changestyle(buttonID);
  setDropClassState(buttonID,buttonClass);
  curButtionID = buttonID;
  divChange();
}
function clickLockoffButton(){
  var buttonID = "lockoff-drop";
  var buttonClass = "dropdown-section";
  changestyle(buttonID);
  setDropClassState(buttonID,buttonClass);
  curButtionID = buttonID;
}
function clickTakeoffButton(){
  var buttonID = "takeoff-drop";
  var buttonClass = "dropdown-section";
  changestyle(buttonID);
  setDropClassState(buttonID,buttonClass);
  curButtionID = buttonID;
}
function clickRtlButton(){
  var buttonID = "rtl-drop";
  var buttonClass = "dropdown-section";
  changestyle(buttonID);
  setDropClassState(buttonID,buttonClass);
  curButtionID = buttonID;
}
function clickLandButton(){
  var buttonID = "land-drop";
  var buttonClass = "dropdown-section";
  changestyle(buttonID);
  setDropClassState(buttonID,buttonClass);
  curButtionID = buttonID;
}
function clickPlayButton(){
  var buttonID = "play-drop";
  var buttonClass = "dropdown-section";
  changestyle(buttonID);
  setDropClassState(buttonID,buttonClass);
  curButtionID = buttonID;
  if(uas_custom_mode == 3){
    if(document.getElementById("play-drop").style.display == 'block'){
        document.getElementById("play-button").style.backgroundImage = 'url(./icon/pause-blue.png)'
      }
      else{
        document.getElementById("play-button").style.backgroundImage = 'url(./icon/pause-grey.png)'
      }
  }
  else{
    if(document.getElementById("play-drop").style.display == 'block'){
        document.getElementById("play-button").style.backgroundImage = 'url(./icon/play-blue.png)'
      }
      else{
        document.getElementById("play-button").style.backgroundImage = 'url(./icon/play-grey.png)'
      }
  }
}
function clickPauseButton(){
  var buttonID = "pause-drop";
  var buttonClass = "dropdown-section";
  changestyle(buttonID);
  setDropClassState(buttonID,buttonClass);
  curButtionID = buttonID;
}
function clickSettingsButton(){
  var buttonID = "settings-drop";
  var buttonClass = "dropdown-section";
  changestyle(buttonID);
  setDropClassState(buttonID,buttonClass);
  curButtionID = buttonID;
}
function clickPlanecenterButton(){
  var buttonID = "planecenter-drop";
  var buttonClass = "dropdown-section";
  changestyle(buttonID);
  setDropClassState(buttonID,buttonClass);
  curButtionID = buttonID;
  init_plane_center();
  save_param_file();
  save_joystick_file();
}

function setDropClassState(buttonID,buttonClass){
  setDropClassNone(buttonID,buttonClass);
  document.getElementById(buttonID).style.display=(document.getElementById(buttonID).style.display!="block")?"block":"none";
  if(document.getElementById("multi-drop").style.display == "none"){
    markers_enable_dragging(false);
  }
  else{
    markers_enable_dragging(true);
  }
  if(buttonID != "templateButton"){
    hideTemplate();
  }
}
function setDropClassNone(buttonID,buttonClass){
  var dropArr = document.getElementsByClassName(buttonClass);
  for(var i=0;i < dropArr.length; i++) {
    if(dropArr[i].style.display=="none" || dropArr[i].id==buttonID) continue;
    else dropArr[i].style.display = "none";
  }
}
function setAllDropClassNone(){
  var dropArr = document.getElementsByClassName("dropdown-section");
  for(var i=0;i < dropArr.length; i++) {
    dropArr[i].style.display = "none";
  }
}
function changestyle(buttonID) {
  var clickID = buttonID.substring(0,buttonID.indexOf('-')+1)+"button";
  changeback(clickID);
  var item = document.getElementById(clickID);
  (document.getElementById(buttonID).style.display!="block")? toBLUE(item) : toGREY(item);
}
function changeback(clickID) {
  for(var i=0;i<tableButtonLiArr.length;i++){
    if(tableButtonLiArr[i].style.backgroundColor!="black"){
      //tableButtonLiArr[i].backgroundColor="black";
      var item = tableButtonLiArr[i].getElementsByTagName("button")[0];
      if(item.id==clickID){ //|| item.id=="connect-button"){
        continue;
      }
      if(!document.getElementById(item.id.substring(0,item.id.indexOf('-')+1)+"button").disabled){
        toGREY(item);
      }
    }
  }
}
function toGREY(item) {
  var clickLi = item.id.substring(0,item.id.indexOf('-')+1)+"li";
  var picname = item.id.substring(0,item.id.indexOf('-')+1)+"grey";
  document.getElementById(clickLi).style.backgroundColor="black";
  if(clickLi=="connect-li") {
    var imgstr = item.style.backgroundImage;
    if(imgstr == 'url("./icon/connect-green.png")' || imgstr == 'url("./icon/connect-red.png")') return;
  }
  item.style.backgroundImage = "url('./icon/"+picname+".png')";
}
function toBLUE(item) {
  var clickLi = item.id.substring(0,item.id.indexOf('-')+1)+"li";
  var picname = item.id.substring(0,item.id.indexOf('-')+1)+"blue";
  document.getElementById(clickLi).style.backgroundColor="white";
  if(clickLi=="connect-li") {
    var imgstr = item.style.backgroundImage;
    if(imgstr == 'url("./icon/connect-green.png")' || imgstr == 'url("./icon/connect-red.png")') return;
  }
  item.style.backgroundImage = "url('./icon/"+picname+".png')";
}

//航点飞行功能按钮
function multiSetOK(){//OK
  //var point_info_item = [1,200.33,15.33,50,"定点转弯"];//函数输入参数，要显示的信息
  var point_info_item = [];
  point_info_table_clear();
  if(gcs_waypoints_list.length == 0) return;
  for(var i=1;i<gcs_waypoints_list.length;i++){
    var alt = gcs_waypoints_list[i].alt.toFixed(1);
    var speed = gcs_waypoints_list[i].speed.toFixed(2);
    var hold_time = gcs_waypoints_list[i].hold_time.toFixed(1);
    var action_name = "";
    switch(gcs_waypoints_list[i].action){
      case WP_ACTION_NOTHING:
        action_name = "无";
        break;
      case WP_ACTION_LAND:
        action_name = "降落";
        break;
      case WP_ACTION_RTL:
        action_name = "返航";
        break;
      default:
        continue;
    }
    point_info_item = [i, alt, speed, hold_time, action_name];
    add_point_info(point_info_item);
  }
  document.getElementById("multi-drop").style.display="none";//隐藏当前页面
  document.getElementById("multi-drop-state").style.display="block";//显示状态页面
  markers_enable_dragging(false);
  // multiAlt=!multiAlt;
}

function multiReturn(){//返回
  document.getElementById("multi-drop-state").style.display="none";//隐藏当前页面
  document.getElementById("multi-drop").style.display="block";//显示状态页面
  markers_enable_dragging(true);
  // multiAlt=!multiAlt;
}

function markers_enable_dragging(enabled) {
  if(enabled){
    for(var i=0;i<waypoint_markers_list.length;i++){
      waypoint_markers_list[i].enableDragging();
    }
  }
  else{
    for(var i=0;i<waypoint_markers_list.length;i++){
      waypoint_markers_list[i].disableDragging();
    }
  }
}

//航点在航点飞行面板显示
var point_edit_list = [];
var multi_input=document.getElementById("flightpoint-area");
function multi_refresh_points(){
  //取得div标签
  for(var i=1;i<point_edit_list.length;i++){
    var imgDiv = point_edit_list[i];
    multi_input.removeChild(imgDiv);
  }
  point_edit_list = [];
  var imgDiv = null;
  //创建要添加的DIV标签
  for(var i=0;i<gcs_waypoints_list.length;i++){
    draw_new_point(i);
  }
}

function draw_new_point(index){
  var imgDiv = document.createElement("BUTTON");
  imgDiv.innerHTML = index;
  //三位数时减小字号
  if(imgDiv.innerHTML > 99) imgDiv.style.fontSize="15px";
  //在div标签下插入一个子节点，即之前声明的DIV标签
  if(index>0){
    multi_input.appendChild(imgDiv);
    //滚动至当前添加航点
    multi_input.scrollTop = multi_input.scrollHeight;
    //某航点在该窗口被选中
    imgDiv.addEventListener('click', function(e){
      if(all_points.checked){
        for(var i=0;i<point_edit_list.length;i++){
          point_edit_list[i].style.background="url('./icon/waypoint.png')";
          point_edit_list[i].style.backgroundSize="100% 100%";
          marker_on_click(cur_clicked_mark);
        }
        all_points.checked = false;
      }
      marker_on_click(imgDiv.innerHTML);
      console.log('point clicked'+ imgDiv.innerHTML)
      cur_clicked_mark = parseInt(imgDiv.innerHTML);
    });
  }
  //将当前点加入list维护
  point_edit_list.push(imgDiv);
}
//航点状态列表显示
var point_info_table = document.getElementById("pointinfo-table");
var point_info_list = [];
var point_info_item = [];//函数输入参数，要显示的信息
function point_info_table_clear() {
  //point_info_table.innerHTML = "";
  //point_info_item = ["航点","高度","速度","停留","动作"];
  //add_point_info(point_info_item);
  var tableRows = point_info_table.getElementsByTagName('tr');
  var rowCount = tableRows.length;
  for (var x=rowCount-1; x > 0; x--) {
    point_info_table.removeChild(tableRows[x]);
  }
}
function add_point_info(list_item){
  var trArea = document.createElement("TR");
  point_info_table.appendChild(trArea);
  for(var i=0;i<list_item.length;i++){
    var tdArea = document.createElement("TD");
    tdArea.innerHTML = list_item[i];
    trArea.appendChild(tdArea);
  }
  //将当前行加入list维护
  point_info_list.push(trArea);
}

//当前 航点状态列表显示
var cur_point_info_table = document.getElementById("viewpoints-table");
var cur_point_info_list = [];
var cur_point_info_item = [];//函数输入参数，要显示的信息

function cur_point_info_table_clear() {
  var tableRows = cur_point_info_table.getElementsByTagName('tr');
  var rowCount = tableRows.length;
  for (var x=rowCount-1; x>0; x--) {
    cur_point_info_table.removeChild(tableRows[x]);
  }
  cur_point_info_list = [];
}

function cur_add_point_info(list_item){
  var trArea = document.createElement("TR");
  cur_point_info_table.appendChild(trArea);
  for(var i=0;i<list_item.length;i++){
    var tdArea = document.createElement("TD");
    tdArea.innerHTML = list_item[i];
    trArea.appendChild(tdArea);
  }
  //将当前行加入list维护
  cur_point_info_list.push(trArea);
}

function update_cur_point_info(){
  for(var i=0;i<cur_point_info_list.length;i++){
    if(i < reached_index){
      cur_point_info_list[i].style.color = "grey";
    }
    else{
      cur_point_info_list[i].style.color = "white";
    }
  }
}

function cur_point_table_display(){
  var cur_point_info_item = [];
  cur_point_info_table_clear();
  for(var i=1;i<gcs_waypoints_list.length;i++){
    var alt = gcs_waypoints_list[i].alt.toFixed(1);
    var speed = gcs_waypoints_list[i].speed.toFixed(2);
    var hold_time = gcs_waypoints_list[i].hold_time.toFixed(1);
    var action_name = "";
    switch(gcs_waypoints_list[i].action){
      case WP_ACTION_NOTHING:
        action_name = "无";
        break;
      case WP_ACTION_LAND:
        action_name = "降落";
        break;
      case WP_ACTION_RTL:
        action_name = "返航";
        break;
      default:
        continue;
    }
    cur_point_info_item = [i, alt, speed, hold_time, action_name];
    cur_add_point_info(cur_point_info_item);
  }
  update_cur_point_info();
}


//全选按钮（全部取消）
var all_points=document.getElementById("all-points");
all_points.addEventListener('click', function(e){
  if(all_points.checked){
    for(var i=0;i<point_edit_list.length;i++){
      point_edit_list[i].style.background="url('./icon/waypoint-dark.png')";
      point_edit_list[i].style.backgroundSize="100% 100%";
    }
  }
  else{
    for(var i=0;i<point_edit_list.length;i++){
      point_edit_list[i].style.background="url('./icon/waypoint.png')";
      point_edit_list[i].style.backgroundSize="100% 100%";
      marker_on_click(cur_clicked_mark);
    }
  }
});

var multi_del_point = document.getElementById('multi-deletepoint');
multi_del_point.addEventListener('click', function(e){
  if(all_points.checked){
    clear_wp_on_map();
    console.log(gcs_waypoints_list)
    multi_refresh_points();
    cur_clicked_mark = -1;
    marker_on_click(cur_clicked_mark);
    all_points.checked = false;
    return;
  }
  if(cur_clicked_mark <= 0 || cur_clicked_mark >= gcs_waypoints_list.length){
    return;
  }
  var cur_index = cur_clicked_mark;
  console.log(cur_index)
  gcs_waypoints_list.splice(cur_index, 1);
  waypoint_markers_list[cur_index].hide();
  waypoint_markers_list.splice(cur_index, 1);
  console.log(cur_index+1)
  for(var i=cur_index;i<gcs_waypoints_list.length;i++){
    //console.log(i)
    marker_set_label(i);
  }
  redraw_waypoint_polyline();
  cur_clicked_mark = cur_index - 1;
  marker_on_click(cur_clicked_mark);
  multi_refresh_points();
});

var multi_add_point = document.getElementById('multi-addpoint');
multi_add_point.addEventListener('click', function (e) {
  console.log('multi add'+cur_clicked_mark)
  console.log(cur_clicked_mark+1 < gcs_waypoints_list.length)
  console.log(cur_clicked_mark+1 )
  if(cur_clicked_mark >= 1 && cur_clicked_mark+1 < gcs_waypoints_list.length){
      var add_index = cur_clicked_mark + 1;
      console.log('multi add new point'+cur_clicked_mark)
      var new_lng = (gcs_waypoints_list[cur_clicked_mark].lng + gcs_waypoints_list[cur_clicked_mark+1].lng)/2;
      var new_lat = (gcs_waypoints_list[cur_clicked_mark].lat + gcs_waypoints_list[cur_clicked_mark+1].lat)/2;
      var gcs_wp = new WayPoint(new_lat, new_lng, gcs_waypoints_list.length, WP_DEFAULT_YAW, WP_DEFAULT_ALT, WP_DEFAULT_SPEED, WP_DEFAULT_TIME, WP_DEFAULT_ACTION);
      gcs_waypoints_list.splice(cur_clicked_mark+1, 0, gcs_wp);
      // add new marker to list
      var bd09 = wgs84tobd09(gcs_wp.lng, gcs_wp.lat);
      draw_new_wp(new BMap.Point(bd09[0], bd09[1]), cur_clicked_mark+1);
      for(var i=cur_clicked_mark;i<gcs_waypoints_list.length;i++){
        marker_set_label(i);
      }
      redraw_waypoint_polyline();
      marker_on_click(add_index);
      cur_clicked_mark = add_index;
  }
});

var heartbeat_button = document.getElementById("heartbeat-button");

// 设置弹窗tab按钮切换
var tabArray = ['channel','parameter','introduction'];
function clickTabButton(tab){
  for(var i=0;i<tabArray.length;i++){
    if(tab==tabArray[i]){
      document.getElementById(tabArray[i]).style.display="block";
      document.getElementById(tabArray[i]+'-button').style.color="black";
      document.getElementById(tabArray[i]+'-button').style.background="white";
    }
    else{
      document.getElementById(tabArray[i]).style.display="none";
      document.getElementById(tabArray[i]+'-button').style.color="white";
      document.getElementById(tabArray[i]+'-button').style.background="black";
    }
  }
}
var tabArray2 = ['planeInfo','flyRecords'];
function clickTabButton2(tab){
  for(var i=0;i<tabArray2.length;i++){
    if(tab==tabArray2[i]){
      document.getElementById(tabArray2[i]).style.display="block";
      document.getElementById(tabArray2[i]+'-button').style.color="black";
      document.getElementById(tabArray2[i]+'-button').style.background="white";
    }
    else{
      document.getElementById(tabArray2[i]).style.display="none";
      document.getElementById(tabArray2[i]+'-button').style.color="white";
      document.getElementById(tabArray2[i]+'-button').style.background="black";
    }
  }
}

//模板飞行
var plen = 100;
var SPOT_SIZE = 40;
var stroke_line = new BMap.Polygon([], {strokeColor:"black", strokeWeight:3, strokeOpacity:0.5});
var rectButton = document.getElementById('templateRect-button');
var circleButton = document.getElementById('templateCircle-button');
var scanButton = document.getElementById('templateScan-button');
var point_icon_ok = new BMap.Icon("icon/ok-blackoval.png", new BMap.Size(SPOT_SIZE, SPOT_SIZE));
var point_icon_cancel = new BMap.Icon("icon/cancel-blackoval.png", new BMap.Size(SPOT_SIZE, SPOT_SIZE));
var point_icon_drag = new BMap.Icon("icon/drag-blackoval.png", new BMap.Size(SPOT_SIZE, SPOT_SIZE));
var point_icon_rotate = new BMap.Icon("icon/rotate-blackoval.png", new BMap.Size(SPOT_SIZE, SPOT_SIZE));
var point_icon_move = new BMap.Icon("icon/move-blackoval.png", new BMap.Size(SPOT_SIZE, SPOT_SIZE));
point_icon_ok.setImageSize(new BMap.Size(SPOT_SIZE, SPOT_SIZE));
point_icon_cancel.setImageSize(new BMap.Size(SPOT_SIZE, SPOT_SIZE));
point_icon_drag.setImageSize(new BMap.Size(SPOT_SIZE, SPOT_SIZE));
point_icon_rotate.setImageSize(new BMap.Size(SPOT_SIZE, SPOT_SIZE));
point_icon_move.setImageSize(new BMap.Size(SPOT_SIZE, SPOT_SIZE));
//button点击样式
function clickedtemplateButton(templateButton){
  var templateButtonList = document.getElementsByClassName('template-button-image');
  for(var i=0;i<templateButtonList.length;i++){
        templateButtonList[i].disabled=false;//能点
  }
  templateButton.style.backgroundImage = templateButton.style.backgroundImage.substring(0,templateButton.style.backgroundImage.indexOf('-')) + "-blue.png\")";
  templateButton.disabled=true;//不能点
}
//获得zoom值改变模板半径
function getLenByZoom(){
  var x;
  switch (map.getZoom())
  {
    case 12:
      x=0.07;
      break;
    case 13:
      x=0.028;
      break;
    case 14:
      x=0.014;
      break;
    case 15:
      x=0.007;
      break;
    case 16:
      x=0.0028;
      break;
    case 17:
      x=0.0014;
      break;
    case 18:
      x=0.0007;
      break;
    case 19:
      x=0.00028;
      break;
  }
  return x;
}
//显示&隐藏div
function divChange(){
  rectButton.disabled=false;
  circleButton.disabled=false;
  scanButton.disabled=false;
  rectButton.style.backgroundImage = "url('./icon/templateRect-grey.png')";
  circleButton.style.backgroundImage = "url('./icon/templateCircle-grey.png')";
  scanButton.style.backgroundImage = "url('./icon/templateScan-grey.png')";
  document.getElementById("template-rect-div").style.display = "none";
  document.getElementById("template-circle-div").style.display = "none";
  document.getElementById("template-scan-div").style.display = "none";
}
var tlmarker;
var trmarker;
var brmarker;
var blmarker;
var cmarker;
var lmarker;
var rmarker;
var bmarker;
var ctmarker;
//隐藏overlay
function hideTemplate(){
    map.removeOverlay(trmarker);
    map.removeOverlay(tlmarker);
    map.removeOverlay(brmarker);
    map.removeOverlay(blmarker);
    map.removeOverlay(cmarker);
    map.removeOverlay(stroke_line);
    map.removeOverlay(lmarker);
    map.removeOverlay(rmarker);
    map.removeOverlay(bmarker);
    map.removeOverlay(ctmarker);
    map.removeOverlay(circle_model);
}
//向量方法判断点和线位置关系
function LeftOfLine(p, p1, p2){
  return (p1.lng-p2.lng)*(p.lat-p2.lat)-(p.lng-p2.lng)*(p1.lat-p2.lat)>0;
}
function LeftOfLine2(p, p1, p2){
  return (p1.x-p2.x)*(p.y-p2.y)-(p.x-p2.x)*(p1.y-p2.y)>0;
}

//模板Rect
function addTemplateRect(fourPoints,centerPoint,fourPixels,centerPixel,len){
  centerPixel = map.pointToPixel(centerPoint);
  tlmarker = new BMap.Marker(fourPoints[0]);
  trmarker = new BMap.Marker(fourPoints[1]);
  brmarker = new BMap.Marker(fourPoints[2]);
  blmarker = new BMap.Marker(fourPoints[3]);
  cmarker = new BMap.Marker(centerPoint);
  tlmarker.setTop(true);
  trmarker.setTop(true);
  brmarker.setTop(true);
  blmarker.setTop(true);
  cmarker.setTop(true);
  tlmarker.setIcon(point_icon_cancel);
  trmarker.setIcon(point_icon_ok);
  brmarker.setIcon(point_icon_drag);
  blmarker.setIcon(point_icon_rotate);
  cmarker.setIcon(point_icon_move);
  blmarker.enableDragging();
  brmarker.enableDragging();
  cmarker.enableDragging();
  //添加按钮
  map.addOverlay(tlmarker);
  map.addOverlay(trmarker);
  map.addOverlay(brmarker);
  map.addOverlay(blmarker);
  map.addOverlay(cmarker);
  //添加dragstart和end事件
  tlmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  trmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  brmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  blmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  cmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  tlmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  trmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  brmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  blmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  cmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  //添加取消事件
  tlmarker.addEventListener('click',function(e){
    hideTemplate();
    // rectButton.disabled=false;
    clickTemplateButton();
    clickTemplateButton();
  });
  //添加拖拽事件
  cmarker.addEventListener('dragging', function(e){
    for(var cou=0;cou<4;cou++){
      fourPixels[cou] = map.pointToPixel(fourPoints[cou]);
    }
    centerPixel = map.pointToPixel(centerPoint);
    //移动图形
    movex = e.point.lng-centerPoint.lng;
    movey = e.point.lat-centerPoint.lat;
    fourPoints[0] = new BMap.Point(fourPoints[0].lng+movex,fourPoints[0].lat+movey);
    fourPoints[1] = new BMap.Point(fourPoints[1].lng+movex,fourPoints[1].lat+movey);
    fourPoints[2] = new BMap.Point(fourPoints[2].lng+movex,fourPoints[2].lat+movey);
    fourPoints[3] = new BMap.Point(fourPoints[3].lng+movex,fourPoints[3].lat+movey);
    trmarker.setPosition(fourPoints[1]);
    blmarker.setPosition(fourPoints[3]);
    tlmarker.setPosition(fourPoints[0]);
    brmarker.setPosition(fourPoints[2]);
    stroke_line.setPath(fourPoints);
    centerPoint=e.point;
  });
  brmarker.addEventListener('dragging', function(e){
    for(var cou=0;cou<4;cou++){
      fourPixels[cou] = map.pointToPixel(fourPoints[cou]);
    }
    centerPixel = map.pointToPixel(centerPoint);
    //拉伸图形，四条边与坐标系的夹角不变
    var alpha = Math.atan((fourPixels[1].y-fourPixels[0].y)/(fourPixels[1].x-fourPixels[0].x));
    var beta = Math.atan((e.pixel.y-centerPixel.y)/(e.pixel.x-centerPixel.x));
    len = Math.sqrt(Math.pow(e.pixel.x-centerPixel.x,2)+Math.pow(e.pixel.y-centerPixel.y,2));
    var midPixel = new BMap.Pixel(centerPixel.x+len*Math.cos(beta-alpha)*Math.cos(alpha), centerPixel.y+len*Math.cos(beta-alpha)*Math.sin(alpha));
    if(e.pixel.x<centerPixel.x){
      midPixel.x = 2*centerPixel.x - midPixel.x;
      midPixel.y = 2*centerPixel.y - midPixel.y;
    }
    fourPixels[2] = e.pixel;
    fourPixels[0].x = centerPixel.x*2-fourPixels[2].x;
    fourPixels[0].y = centerPixel.y*2-fourPixels[2].y;
    fourPixels[1].x = midPixel.x*2-fourPixels[2].x;
    fourPixels[1].y = midPixel.y*2-fourPixels[2].y;
    fourPixels[3].x = centerPixel.x*2-fourPixels[1].x;
    fourPixels[3].y = centerPixel.y*2-fourPixels[1].y;
    for(var cou=0;cou<4;cou++){
      fourPoints[cou] = map.pixelToPoint(fourPixels[cou]);
    }

    trmarker.setPosition(fourPoints[1]);
    blmarker.setPosition(fourPoints[3]);
    tlmarker.setPosition(fourPoints[0]);
    brmarker.setPosition(fourPoints[2]);
    stroke_line.setPath(fourPoints);
  });
  //添加旋转事件
  blmarker.addEventListener('dragging', function(e){
    for(var cou=0;cou<4;cou++){
      fourPixels[cou] = map.pointToPixel(fourPoints[cou]);
    }
    centerPixel = map.pointToPixel(centerPoint);
    //旋转图形,图形形状不变
    var oldAngel = Math.atan((fourPixels[3].y-centerPixel.y)/(fourPixels[3].x-centerPixel.x));
    var newAngel = Math.atan((e.pixel.y-centerPixel.y)/(e.pixel.x-centerPixel.x));
    var altAngel = Math.atan((fourPixels[0].y-centerPixel.y)/(fourPixels[0].x-centerPixel.x));
    var newAltAngel = altAngel + newAngel - oldAngel;
    //超过90度的bug修复 console.log(altAngel/Math.PI*180+";"+newAltAngel/Math.PI*180);
    if(newAltAngel<-Math.PI/2||newAltAngel>Math.PI/2){
      fourPixels[2].x = centerPixel.x - len*Math.cos(newAltAngel);
      fourPixels[2].y = centerPixel.y - len*Math.sin(newAltAngel);
      fourPixels[0].x = centerPixel.x*2-fourPixels[2].x;
      fourPixels[0].y = centerPixel.y*2-fourPixels[2].y;
    }
    else{
      fourPixels[0].x = centerPixel.x - len*Math.cos(newAltAngel);
      fourPixels[0].y = centerPixel.y - len*Math.sin(newAltAngel);
      fourPixels[2].x = centerPixel.x*2-fourPixels[0].x;
      fourPixels[2].y = centerPixel.y*2-fourPixels[0].y;
    }
    var L = Math.sqrt(Math.pow(e.pixel.x-centerPixel.x,2)+Math.pow(e.pixel.y-centerPixel.y,2))/len;
    var moveX = (e.pixel.x-centerPixel.x)/L;
    var moveY = (e.pixel.y-centerPixel.y)/L;
    var movePixel = new BMap.Pixel(centerPixel.x+moveX,centerPixel.y+moveY);
    fourPixels[3] = movePixel;
    fourPixels[1].x = centerPixel.x*2-fourPixels[3].x;
    fourPixels[1].y = centerPixel.y*2-fourPixels[3].y;
    //旋转突变的bug修复 console.log(LeftOfLine(fourPixels[3], fourPixels[0], fourPixels[2]));
    if(LeftOfLine2(fourPixels[3], fourPixels[0], fourPixels[2])){
      var tempPixel = fourPixels[0];
      fourPixels[0] = fourPixels[2];
      fourPixels[2] = tempPixel;
    }

    for(var cou=0;cou<4;cou++){
      fourPoints[cou] = map.pixelToPoint(fourPixels[cou]);
    }
    trmarker.setPosition(fourPoints[1]);
    blmarker.setPosition(fourPoints[3]);
    tlmarker.setPosition(fourPoints[0]);
    brmarker.setPosition(fourPoints[2]);
    stroke_line.setPath(fourPoints);
  });
  //添加确认事件
  trmarker.addEventListener('click', function(){
    marker_clicked = true;
    var rect_select1 = document.getElementById('template-rect-select1');
    var index = Number(rect_select1.options[rect_select1.selectedIndex].value);
    var res = new Array();
    res.push(fourPoints[index]);
    res.push(fourPoints[(index+1)%4]);
    res.push(fourPoints[(index+2)%4]);
    res.push(fourPoints[(index+3)%4]);
    var rect_select2 = document.getElementById('template-rect-select2');
    if(rect_select2.value=="1"){
      var temp = res[1];
      res[1]=res[3];
      res[3]=temp;
    }
    addFlightPoints(res);
  });
}
function drawTemplateRect(){
  clear_wp_on_map();
  divChange();
  document.getElementById('template-rect-div').style.display = "block";
  //设置按钮不能被点击（防止再添加图形）
  clickedtemplateButton(rectButton);
  //清空当前覆盖物
  hideTemplate();
  var centerPoint = map.getBounds().getCenter();
  //根据当前zoom获得len
  var len = getLenByZoom();
  centerPoint.lat = centerPoint.lat+len;//获取当前屏幕中心坐标
  var centerPixel = map.pointToPixel(centerPoint);
  //初始化点坐标
  var fourPoints = new Array();
  var fourPixels = new Array();
  fourPixels.push(new BMap.Pixel(centerPixel.x-plen,centerPixel.y-plen));
  fourPixels.push(new BMap.Pixel(centerPixel.x+plen,centerPixel.y-plen));
  fourPixels.push(new BMap.Pixel(centerPixel.x+plen,centerPixel.y+plen));
  fourPixels.push(new BMap.Pixel(centerPixel.x-plen,centerPixel.y+plen));
  for(var cou=0;cou<4;cou++){
    fourPoints[cou] = map.pixelToPoint(fourPixels[cou]);
  }
  //添加事件
  addTemplateRect(fourPoints,centerPoint,fourPixels,centerPixel,plen*Math.sqrt(2));
  //初始化线
  stroke_line.setPath(fourPoints);
  map.addOverlay(stroke_line);
}

//模板多边形Circle
var centre_radius = document.getElementById('centreRadius');
var circle_model = new BMap.Circle(new BMap.Point(0,0),0, {strokeColor:"black", strokeWeight:3, strokeOpacity:0.5});
//function addTemplateCircle(circle_point_list,radius,centerPoint){
function addTemplateCircle(radius,radiusP,centerPoint,centerPixel){
  var angle = Math.PI/2;
  var threePixels = new Array();
  threePixels.push(new BMap.Pixel(centerPixel.x-radiusP*Math.cos(Math.PI/6),centerPixel.y-radiusP/2));
  threePixels.push(new BMap.Pixel(centerPixel.x+radiusP*Math.cos(Math.PI/6),centerPixel.y-radiusP/2));
  threePixels.push(new BMap.Pixel(centerPixel.x,centerPixel.y+radiusP));
  var threePoints = new Array();
  threePoints.push(map.pixelToPoint(threePixels[0]));
  threePoints.push(map.pixelToPoint(threePixels[1]));
  threePoints.push(map.pixelToPoint(threePixels[2]));
  //设置marker
  rmarker = new BMap.Marker(threePoints[1]);
  bmarker = new BMap.Marker(threePoints[2]);
  lmarker = new BMap.Marker(threePoints[0]);
  ctmarker = new BMap.Marker(centerPoint);
  lmarker.setTop(true);
  rmarker.setTop(true);
  bmarker.setTop(true);
  ctmarker.setTop(true);
  lmarker.setIcon(point_icon_cancel);
  rmarker.setIcon(point_icon_ok);
  bmarker.setIcon(point_icon_drag);
  ctmarker.setIcon(point_icon_move);
  ctmarker.enableDragging();
  bmarker.enableDragging();
  //添加按钮
  map.addOverlay(lmarker);
  map.addOverlay(rmarker);
  map.addOverlay(bmarker);
  map.addOverlay(ctmarker);
  //
  rmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  bmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  lmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  ctmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  rmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  bmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  lmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  ctmarker.addEventListener('dragend', function(e){marker_dragged = false;});

  circle_model.setRadius(radius);
  circle_model.setCenter(centerPoint);
  map.addOverlay(circle_model);
  //添加取消事件
  lmarker.addEventListener('click',function(e){
    hideTemplate();
    // circleButton.disabled=false;
    clickTemplateButton();
    clickTemplateButton();
  });
  //添加拖拽事件
  ctmarker.addEventListener('dragging', function(e){
    for(var cou=0;cou<3;cou++){
      threePixels[cou] = map.pointToPixel(threePoints[cou]);
    }
    centerPixel =  map.pointToPixel(centerPoint);
    //移动图形
    movex = e.pixel.x-centerPixel.x;
    movey = e.pixel.y-centerPixel.y;
    circle_model.setCenter(e.point);
    centerPoint=e.point;
    for(var cou=0;cou<3;cou++){
      threePixels[cou].x = threePixels[cou].x+movex;
      threePixels[cou].y = threePixels[cou].y+movey;
    }

    for(var cou=0;cou<3;cou++){
      threePoints[cou] = map.pixelToPoint(threePixels[cou]);
    }
    lmarker.setPosition(threePoints[0]);
    rmarker.setPosition(threePoints[1]);
    bmarker.setPosition(threePoints[2]);
    document.getElementById('centreLng').value = centerPoint.lng;
    document.getElementById('centreLat').value = centerPoint.lat;
  });
  bmarker.addEventListener('dragging', function(e){
    for(var cou=0;cou<3;cou++){
      threePixels[cou] = map.pointToPixel(threePoints[cou]);
    }
    centerPixel =  map.pointToPixel(centerPoint);
    //拉伸图形
    radius = map.getDistance(e.point,centerPoint);
    circle_model.setRadius(radius);
    radiusP = Math.sqrt(Math.pow(e.pixel.x-centerPixel.x,2)+Math.pow(e.pixel.y-centerPixel.y,2));
    angle = Math.atan((e.pixel.y-centerPixel.y)/(e.pixel.x-centerPixel.x));
    if(e.pixel.x < centerPixel.x) angle = angle + Math.PI;
    if(e.pixel.x == centerPixel.x){
      if(e.pixel.y < centerPixel.y) angle = Math.PI/2;
      else angle = Math.PI*3/2;
    }
    threePixels[0] = new BMap.Pixel(centerPixel.x+radiusP*Math.cos(angle+Math.PI*2/3),centerPixel.y+radiusP*Math.sin(angle+Math.PI*2/3));
    threePixels[1] = new BMap.Pixel(centerPixel.x+radiusP*Math.cos(angle-Math.PI*2/3),centerPixel.y+radiusP*Math.sin(angle-Math.PI*2/3));
    threePixels[2] = e.pixel;

    for(var cou=0;cou<3;cou++){
      threePoints[cou] = map.pixelToPoint(threePixels[cou]);
    }
    centre_radius.value = radius;
    lmarker.setPosition(threePoints[0]);
    rmarker.setPosition(threePoints[1]);
    bmarker.setPosition(threePoints[2]);
  });
  //添加确认事件
  rmarker.addEventListener('click', function(){
    marker_clicked = true;
    centerPixel =  map.pointToPixel(centerPoint);
    var return_list = new Array();
    var point_count = document.getElementById("centrePointCount").value;
    var circle_select = document.getElementById("template-circle-select").value;
    var polyAngle;
    if(circle_select=="1"){
      for(i=0;i<point_count;i++){
        polyAngle = angle - (2* Math.PI / point_count) * i;
        return_list.push(map.pixelToPoint(new BMap.Pixel(centerPixel.x+Math.cos(polyAngle)*radiusP, centerPixel.y+Math.sin(polyAngle)*radiusP)));
      }
    }
    else{
      for(i=0;i<point_count;i++){
        polyAngle = angle + (2* Math.PI / point_count) * i;
        return_list.push(map.pixelToPoint(new BMap.Pixel(centerPixel.x+Math.cos(polyAngle)*radiusP, centerPixel.y+Math.sin(polyAngle)*radiusP)));
      }
    }
    addFlightPoints(return_list);
  });
  //监听信息修改事件
  // centre_radius.addEventListener('blur',function(){
  //   centerPixel =  map.pointToPixel(centerPoint);
  //   radius = centre_radius.value;
  //   circle_model.setRadius(radius);
  //   //radiusP
  //   var threePixels = new Array();
  //   threePixels[0] = new BMap.Pixel(centerPixel.x-radiusP*Math.cos(Math.PI/6),centerPixel.y-radiusP/2);
  //   threePixels[1] = new BMap.Pixel(centerPixel.x+radiusP*Math.cos(Math.PI/6),centerPixel.y-radiusP/2);
  //   threePixels[2] = new BMap.Pixel(centerPixel.x,centerPixel.y+radiusP);
  //   var threePoints = new Array();
  //   threePoints.push(map.pixelToPoint(threePixels[0]));
  //   threePoints.push(map.pixelToPoint(threePixels[1]));
  //   threePoints.push(map.pixelToPoint(threePixels[2]));
  //   lmarker.setPosition(threePoints[0]);
  //   rmarker.setPosition(threePoints[1]);
  //   bmarker.setPosition(threePoints[2]);
  // });
}
function drawTemplateCircle(){

  clear_wp_on_map();
  divChange();
  document.getElementById('template-circle-div').style.display = "block";
  //设置当前按钮不能被点击
  clickedtemplateButton(circleButton);
  //清空当前覆盖物
  hideTemplate();
  //初始化圆心坐标和半径
  var radiusP = 101;
  var centerPixel = map.pointToPixel(map.getBounds().getCenter());
  centerPixel.y = centerPixel.y-radiusP;
  var centerPoint = map.pixelToPoint(centerPixel);
  var radius = map.getDistance(map.getBounds().getCenter(), centerPoint);//圆初始半径（单位：米）

  //console.log(map.pointToPixel(map.getBounds().getCenter()),centerPixel);
  //当前参数信息显示
  document.getElementById('centreLng').value = centerPoint.lng;
  document.getElementById('centreLat').value = centerPoint.lat;
  centre_radius.value = radius;
  //绘制多边形按钮
  addTemplateCircle(radius,radiusP,centerPoint,centerPixel);
}

//模板Scan
function addTemplateScan(fourPoints,centerPoint,fourPixels,centerPixel,len){
  //设置矩形四角marker
  tlmarker = new BMap.Marker(fourPoints[0]);
  trmarker = new BMap.Marker(fourPoints[1]);
  brmarker = new BMap.Marker(fourPoints[2]);
  blmarker = new BMap.Marker(fourPoints[3]);
  cmarker = new BMap.Marker(centerPoint);
  tlmarker.setTop(true);
  trmarker.setTop(true);
  brmarker.setTop(true);
  blmarker.setTop(true);
  cmarker.setTop(true);
  tlmarker.setIcon(point_icon_cancel);
  trmarker.setIcon(point_icon_ok);
  brmarker.setIcon(point_icon_drag);
  blmarker.setIcon(point_icon_rotate);
  cmarker.setIcon(point_icon_move);
  blmarker.enableDragging();
  brmarker.enableDragging();
  cmarker.enableDragging();
  //添加按钮
  map.addOverlay(tlmarker);
  map.addOverlay(trmarker);
  map.addOverlay(brmarker);
  map.addOverlay(blmarker);
  map.addOverlay(cmarker);
  //添加dragstart和end事件
  tlmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  trmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  brmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  blmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  cmarker.addEventListener('dragstart', function(e){marker_dragged = true;});
  tlmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  trmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  brmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  blmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  cmarker.addEventListener('dragend', function(e){marker_dragged = false;});
  //添加取消事件
  tlmarker.addEventListener('click',function(e){
    hideTemplate();
    //scanButton.disabled=false;
    clickTemplateButton();
    clickTemplateButton();
  });
  //添加拖拽事件
  cmarker.addEventListener('dragging', function(e){
    for(var cou=0;cou<4;cou++){
      fourPixels[cou] = map.pointToPixel(fourPoints[cou]);
    }
    centerPixel = map.pointToPixel(centerPoint);
    //移动图形
    movex = e.point.lng-centerPoint.lng;
    movey = e.point.lat-centerPoint.lat;
    fourPoints[0] = new BMap.Point(fourPoints[0].lng+movex,fourPoints[0].lat+movey);
    fourPoints[1] = new BMap.Point(fourPoints[1].lng+movex,fourPoints[1].lat+movey);
    fourPoints[2] = new BMap.Point(fourPoints[2].lng+movex,fourPoints[2].lat+movey);
    fourPoints[3] = new BMap.Point(fourPoints[3].lng+movex,fourPoints[3].lat+movey);

    trmarker.setPosition(fourPoints[1]);
    blmarker.setPosition(fourPoints[3]);
    tlmarker.setPosition(fourPoints[0]);
    brmarker.setPosition(fourPoints[2]);
    stroke_line.setPath(fourPoints);
    centerPoint=e.point;
  });
  brmarker.addEventListener('dragging', function(e){
    for(var cou=0;cou<4;cou++){
      fourPixels[cou] = map.pointToPixel(fourPoints[cou]);
    }
    centerPixel = map.pointToPixel(centerPoint);
    //拉伸图形，四条边与坐标系的夹角不变
    var alpha = Math.atan((fourPixels[1].y-fourPixels[0].y)/(fourPixels[1].x-fourPixels[0].x));
    var beta = Math.atan((e.pixel.y-centerPixel.y)/(e.pixel.x-centerPixel.x));
    len = Math.sqrt(Math.pow(e.pixel.x-centerPixel.x,2)+Math.pow(e.pixel.y-centerPixel.y,2));
    var midPixel = new BMap.Pixel(centerPixel.x+len*Math.cos(beta-alpha)*Math.cos(alpha), centerPixel.y+len*Math.cos(beta-alpha)*Math.sin(alpha));
    if(e.pixel.x<centerPixel.x){
      midPixel.x = 2*centerPixel.x - midPixel.x;
      midPixel.y = 2*centerPixel.y - midPixel.y;
    }
    fourPixels[2] = e.pixel;
    fourPixels[0].x = centerPixel.x*2-fourPixels[2].x;
    fourPixels[0].y = centerPixel.y*2-fourPixels[2].y;
    fourPixels[1].x = midPixel.x*2-fourPixels[2].x;
    fourPixels[1].y = midPixel.y*2-fourPixels[2].y;
    fourPixels[3].x = centerPixel.x*2-fourPixels[1].x;
    fourPixels[3].y = centerPixel.y*2-fourPixels[1].y;

    for(var cou=0;cou<4;cou++){
      fourPoints[cou] = map.pixelToPoint(fourPixels[cou]);
    }
    trmarker.setPosition(fourPoints[1]);
    blmarker.setPosition(fourPoints[3]);
    tlmarker.setPosition(fourPoints[0]);
    brmarker.setPosition(fourPoints[2]);
    stroke_line.setPath(fourPoints);
  });
  //添加旋转事件
  blmarker.addEventListener('dragging', function(e){
    for(var cou=0;cou<4;cou++){
      fourPixels[cou] = map.pointToPixel(fourPoints[cou]);
    }
    centerPixel = map.pointToPixel(centerPoint);
    //旋转图形,图形形状不变
    var oldAngel = Math.atan((fourPixels[3].y-centerPixel.y)/(fourPixels[3].x-centerPixel.x));
    var newAngel = Math.atan((e.pixel.y-centerPixel.y)/(e.pixel.x-centerPixel.x));
    var altAngel = Math.atan((fourPixels[0].y-centerPixel.y)/(fourPixels[0].x-centerPixel.x));
    var newAltAngel = altAngel + newAngel - oldAngel;
    if(newAltAngel<-Math.PI/2||newAltAngel>Math.PI/2){
      fourPixels[2].x = centerPixel.x - len*Math.cos(newAltAngel);
      fourPixels[2].y = centerPixel.y - len*Math.sin(newAltAngel);
      fourPixels[0].x = centerPixel.x*2-fourPixels[2].x;
      fourPixels[0].y = centerPixel.y*2-fourPixels[2].y;
    }
    else{
      fourPixels[0].x = centerPixel.x - len*Math.cos(newAltAngel);
      fourPixels[0].y = centerPixel.y - len*Math.sin(newAltAngel);
      fourPixels[2].x = centerPixel.x*2-fourPixels[0].x;
      fourPixels[2].y = centerPixel.y*2-fourPixels[0].y;
    }
    var L = Math.sqrt(Math.pow(e.pixel.x-centerPixel.x,2)+Math.pow(e.pixel.y-centerPixel.y,2))/len;
    var moveX = (e.pixel.x-centerPixel.x)/L;
    var moveY = (e.pixel.y-centerPixel.y)/L;
    var movePixel = new BMap.Pixel(centerPixel.x+moveX,centerPixel.y+moveY);
    fourPixels[3] = movePixel;
    fourPixels[1].x = centerPixel.x*2-fourPixels[3].x;
    fourPixels[1].y = centerPixel.y*2-fourPixels[3].y;
    if(LeftOfLine2(fourPixels[3], fourPixels[0], fourPixels[2])){
      var tempPixel = fourPixels[0];
      fourPixels[0] = fourPixels[2];
      fourPixels[2] = tempPixel;
    }

    for(var cou=0;cou<4;cou++){
      fourPoints[cou] = map.pixelToPoint(fourPixels[cou]);
    }
    trmarker.setPosition(fourPoints[1]);
    blmarker.setPosition(fourPoints[3]);
    tlmarker.setPosition(fourPoints[0]);
    brmarker.setPosition(fourPoints[2]);
    stroke_line.setPath(fourPoints);
  });
  //添加确认事件
  trmarker.addEventListener('click', function(){
    marker_clicked = true;
    var rect_select1 = document.getElementById('template-scan-select1');
    var index1 = rect_select1.options[rect_select1.selectedIndex].value;
    var rect_select2 = document.getElementById('template-scan-select2');
    var index2 = rect_select2.options[rect_select2.selectedIndex].value;
    var list = [];
    console.log(index1,index2);
    if(index2==0){
      switch(index1){
        case "0":
        list = getScanList(fourPoints,0,1);
        break;
        case "1":
        list = getScanList(fourPoints,1,0);
        break;
        case "2":
        list = getScanList(fourPoints,2,3);
        break;
        case "3":
        list = getScanList(fourPoints,3,2);
        break;
      }
    }else{
      switch(index1){
        case "0":
        list = getScanList(fourPoints,0,3);
        break;
        case "1":
        list = getScanList(fourPoints,1,2);
        break;
        case "2":
        list = getScanList(fourPoints,2,1);
        break;
        case "3":
        list = getScanList(fourPoints,3,0);
        break;
      }
    }
    addFlightPoints(list);
  });
}
function drawTemplateScan(){
  clear_wp_on_map();
  divChange();
  document.getElementById('template-scan-div').style.display = "block";
  //设置按钮不能被点击（防止再添加图形）
  clickedtemplateButton(scanButton);
  //清空当前覆盖物
  hideTemplate();
  //获取当前屏幕中心坐标
  var centerPoint = map.getBounds().getCenter();
  var len = getLenByZoom();
  centerPoint.lat = centerPoint.lat+len;
  var centerPixel = map.pointToPixel(centerPoint);
  //初始化点坐标
  var fourPoints = new Array();
  var fourPixels = new Array();
  fourPixels.push(new BMap.Pixel(centerPixel.x-plen,centerPixel.y-plen));
  fourPixels.push(new BMap.Pixel(centerPixel.x+plen,centerPixel.y-plen));
  fourPixels.push(new BMap.Pixel(centerPixel.x+plen,centerPixel.y+plen));
  fourPixels.push(new BMap.Pixel(centerPixel.x-plen,centerPixel.y+plen));
  for(var cou=0;cou<4;cou++){
    fourPoints[cou] = map.pixelToPoint(fourPixels[cou]);
  }
  //添加事件
  addTemplateScan(fourPoints,centerPoint,fourPixels,centerPixel,plen*Math.sqrt(2));
  //初始化线
  stroke_line.setPath(fourPoints);
  map.addOverlay(stroke_line);
}
function getScanList(fourPoints,a,b){
  var c = (b+2)%4;
  var d = (a+2)%4;
  var scan_interval = document.getElementById('scan-interval').value;
  var N = Math.floor(getGreatCircleDistance(fourPoints[a].lng,fourPoints[a].lat,fourPoints[c].lng,fourPoints[c].lat)/scan_interval);
  var ylng = fourPoints[b].lng - fourPoints[a].lng;
  var ylat = fourPoints[b].lng - fourPoints[a].lng;
  var xlng = (fourPoints[c].lng - fourPoints[a].lng)/N;
  var xlat = (fourPoints[c].lat - fourPoints[a].lat)/N;
  var scanList = [];
  scanList.push(fourPoints[a]);
  for(var i=1;i<=N;i++){
    z=(i%2==0)?a:b;
    scanList.push(new BMap.Point(fourPoints[z].lng+(i-1)*xlng,fourPoints[z].lat+(i-1)*xlat));
    scanList.push(new BMap.Point(fourPoints[z].lng+(i)*xlng,fourPoints[z].lat+(i)*xlat));
  }
  scanList.push((N%2==0)?fourPoints[d]:fourPoints[c]);
  return scanList;
}
//经纬度计算距离,单位M
var EARTH_RADIUS = 6378137.0;
function getRad(d){
  return d*Math.PI/180.0;
}
function getGreatCircleDistance(lng1,lat1,lng2,lat2){
  var radLat1 = getRad(lat1);
  var radLat2 = getRad(lat2);
  var a = radLat1 - radLat2;
  var b = getRad(lng1) - getRad(lng2);
  var s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
  s = s*EARTH_RADIUS;
  s = Math.round(s*10000)/10000.0;
  return s;
}

//生成航点
function addFlightPoints(list){
  console.log(list)
  hideTemplate();
  //生成航点
  gcs_waypoints_list.push(home_wp);
  var bd09 = wgs84tobd09(home_wp.lng, home_wp.lat);
  draw_new_wp(new BMap.Point(bd09[0], bd09[1]), 0);
  for(var i=0;i<list.length;i++){
    var wgs84 = bd09towgs84(list[i].lng, list[i].lat);
    var gcs_wp = new WayPoint(wgs84[1], wgs84[0], gcs_waypoints_list.length, WP_DEFAULT_YAW, WP_DEFAULT_ALT, WP_DEFAULT_SPEED, WP_DEFAULT_TIME, WP_DEFAULT_ACTION);
    gcs_waypoints_list.push(gcs_wp);
    draw_new_wp(new BMap.Point(list[i].lng, list[i].lat), i+1);
  }
  console.log(waypoint_markers_list);
  redraw_waypoint_polyline();
  multi_refresh_points();

  cur_clicked_mark = gcs_waypoints_list.length - 1;
  marker_on_click(cur_clicked_mark);
 //切换至航点界面
  clickMultiButton();
}

// 悬浮窗下拉框
function replay_drop(){
  document.getElementById('replay-drop').style.display=(document.getElementById('replay-drop').style.display!="block")?"block":"none";
}
function viewPointsSelect() {
  var downselect_button = document.getElementById('downselect-button');
  var viewpoints = document.getElementById('viewpoints-selector');
  if(viewpoints.style.display!="block"){
    viewpoints.style.display = "block";
    downselect_button.style.backgroundImage = "url('./icon/upselect.png')";
  }
  else{
    viewpoints.style.display = "none";
    downselect_button.style.backgroundImage = "url('./icon/downselect.png')";
  }
  cur_point_table_display();
}

// 飞行记录一条记录转为DIV添加到列表中
var flyRecords_area = document.getElementById('flyRecords-area');
function draw_record(flight_record, index){ //应传入一条记录的json参数
  var flyRecords_div = document.createElement('DIV');
  flyRecords_div.className = "flyRecords-div";
  //添加第一行信息
  var flyRecords_ul = document.createElement('DIV');
  flyRecords_ul.className = "flyRecords-ul";
  var flyRecords_li = document.createElement('DIV');
  flyRecords_li.className = "flyRecords-li";
  flyRecords_li.style.width = "300px";
  flyRecords_li.innerHTML = flight_record.date; //FIXME: 飞行时刻
  flyRecords_ul.appendChild(flyRecords_li);
  var flyRecords_li = document.createElement('DIV');
  flyRecords_li.className = "flyRecords-li";
  var flyRecords_button = document.createElement('BUTTON');
  flyRecords_button.innerHTML = "记录回放";
  flyRecords_button.value = flight_record.filename; //FIXME: button的value记录index
  flyRecords_button.onclick = function(){
    record_replay(this.value);
  };//传入参数为被选中记录的index
  flyRecords_li.appendChild(flyRecords_button);
  flyRecords_ul.appendChild(flyRecords_li);
  flyRecords_div.appendChild(flyRecords_ul);
  //添加第二行信息
  var flyRecords_ul = document.createElement('DIV');
  flyRecords_ul.className = "flyRecords-ul";
  var flyRecords_li = document.createElement('DIV');
  flyRecords_li.className = "flyRecords-li";
  flyRecords_li.style.width = "300px";
  var flyRecords_span = document.createElement('SPAN');
  flyRecords_span.innerHTML = flight_record.loc; //FIXME: 飞行地点
  flyRecords_span.className = "flyRecords-span-pos";
  flyRecords_li.appendChild(flyRecords_span);
  flyRecords_ul.appendChild(flyRecords_li);
  var flyRecords_li = document.createElement('DIV');
  flyRecords_li.className = "flyRecords-li2";
  var flyRecords_span = document.createElement('SPAN');
  flyRecords_span.innerHTML = (flight_record.time/60).toFixed(0) + '分'+ (flight_record.time%60).toFixed(0) + '秒'; //FIXME: 飞行时长
  flyRecords_span.className = "flyRecords-span-time";
  flyRecords_li.appendChild(flyRecords_span);
  flyRecords_ul.appendChild(flyRecords_li);
  flyRecords_div.appendChild(flyRecords_ul);
  //添加分割线
  var flyRecords_line = document.createElement('IMG');
  flyRecords_line.className = "flyRecords-line";
  flyRecords_line.src = "icon/split-row.png";
  flyRecords_div.appendChild(flyRecords_line);
  //添加记录到area
  flyRecords_area.appendChild(flyRecords_div);
}
function clear_records(){
  var flyRecords_area_children = flyRecords_area.getElementsByTagName('DIV');
  for(var i=0; i<flyRecords_area_children.length; ){
    if(flyRecords_area_children[i].className == 'flyRecords-div'){
      flyRecords_area.removeChild(flyRecords_area_children[i]);
    }
    else i++;
  }
}

function modify_position(index, pos_info){
  var flyRecords_area_children = flyRecords_area.getElementsByClassName('flyRecords-div');
  var flyRecords_uls = flyRecords_area_children[index].getElementsByTagName('DIV');
  for(var j=0; j < flyRecords_uls.length; j++){
    if(flyRecords_uls[j].className != 'flyRecords-ul') continue;
    var flyRecords_lis = flyRecords_uls[j].getElementsByTagName('DIV');
    for(var k=0; k < flyRecords_lis.length; k++){
      if(flyRecords_lis[k].className != 'flyRecords-li') continue;
      var flyRecords_spans = flyRecords_lis[k].getElementsByTagName('SPAN');
      for(var l=0; l < flyRecords_spans.length; l++){
        if(flyRecords_spans[l].className != 'flyRecords-span-pos') continue;
        //修改信息
        flyRecords_spans[l].innerHTML = pos_info;
      }
    }
  }
}

function update_plane_info(uav_number){
  if(uav_number.substring(0,1) == "X"){//XUEXIAO
    document.getElementById('planeInfo-name-ch').innerHTML = "雪鸮";
    document.getElementById('planeInfo-type').innerHTML = "TXXX-1";
    document.getElementById('planeInfo-size').innerHTML = "尺寸：1570mm*1590mm*420mm";
    document.getElementById('planeInfo-weight').innerHTML = "重量：10kg";
    document.getElementById('planeInfo-endurance-time').innerHTML = "续航时间：70min";
    document.getElementById('planeInfo-maxheight').innerHTML = "飞行高度：4km";
    document.getElementById('planeInfo-maxradius').innerHTML = "飞行半径：5km";
  }
}
